import 'dart:math';

import 'package:flutter/material.dart';
import 'package:fluttery/gestures.dart';
import '_const.dart';
import 'egg_time_knob.dart';
import 'model/egg_timer.dart';
import 'painter_ticker.dart';
import 'package:rxdart/rxdart.dart';

class EggTimeDial extends StatefulWidget {
  final Duration maxTime;
  final int tickPersection;
  const EggTimeDial({
    Key key,
    this.maxTime = const Duration(minutes: 60),
    this.tickPersection: 5,
  }) : super(key: key);
  @override
  _EggTimeDialState createState() => _EggTimeDialState();
}

class _EggTimeDialState extends State<EggTimeDial> {
  double _rotation(Duration current) =>
      2 * pi * current.inSeconds / widget.maxTime.inSeconds;

  @override
  Widget build(BuildContext context) {
    return DialTurnGuestureDetector(
      /// UPDATION HERE
      onDragDiff: (double diff) => EggTimer.inst
          .dial((widget.maxTime.inSeconds * diff / 2 / pi).round()),
      onDragEndFire: () {
        EggTimer.inst.intergerStartTime();
        EggTimer.inst.emitEvent(TimerEvent.start);
      },
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 45),
        width: double.infinity,
        child: AspectRatio(
          aspectRatio: 1.0,
          child: Container(
            //第一个圆
            padding: EdgeInsets.all(55), //内溢
            decoration: BoxDecoration(
                shape: BoxShape.circle,
                color: Colors.blue,
                gradient: LinearGradient(
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter,
                    colors: [
                      gradient_top_color,
                      gradient_bottom_color,
                    ]),
                boxShadow: [
                  BoxShadow(
                      color: Color(0x44000000),
                      blurRadius: 2,
                      spreadRadius: 1,
                      offset: Offset(0, 1.0))
                ]),
            child: Stack(
              children: <Widget>[
                Container(
                  width: double.infinity,
                  height: double.infinity,
                  child: CustomPaint(
                    painter: TickerPainter(
                        tickCount: widget.maxTime.inMinutes,
                        ticksPersection: widget.tickPersection),
                  ),
                ),
                StreamBuilder(
                    stream: Observable.merge([EggTimer.inst.ticking, EggTimer.inst.dialing]),
                    builder: (context, snapshot) {
                      return EggTimeKnob(
                        rotation:
                            snapshot.hasData ? _rotation(EggTimer.inst.currentTime) : 0,
                      );
                    }),
              ],
            ),
          ),
        ),
      ),
    );
  }
  void dispose(){
    EggTimer.inst.t?.cancel();
    super.dispose();
  }
}

class DialTurnGuestureDetector extends StatefulWidget {
  final Widget child;
  final Function(double diff) onDragDiff;
  final Function() onDragEndFire;
  const DialTurnGuestureDetector(
      {Key key, this.child, this.onDragDiff, this.onDragEndFire})
      : super(key: key);
  @override
  _DialTurnGuestureDetectorState createState() =>
      _DialTurnGuestureDetectorState();
}

class _DialTurnGuestureDetectorState extends State<DialTurnGuestureDetector> {
  double base;
  PolarCoord startPolarCoord;
  @override
  Widget build(BuildContext context) {
    return RadialDragGestureDetector(
      onRadialDragStart: onRadialDragStart,
      onRadialDragUpdate: onRadialDragUpdate,
      onRadialDragEnd: onRadialDragEnd,
      child: widget.child,
    );
  }

  onRadialDragStart(PolarCoord startCoord) {
    //print('start .... $startCoord');
    this.startPolarCoord = startCoord;
    this.base = 0;
  }

  onRadialDragUpdate(PolarCoord updateCoord) {
    if (startPolarCoord != null) {
      final diff = updateCoord.angle - startPolarCoord.angle;
      //print('update .... $updateCoord ----- diff $diff');
      widget.onDragDiff(diff);
      this.base += diff;
    }
    startPolarCoord = updateCoord;
  }

  onRadialDragEnd() {
    print('....end Radial dragging :::${(base / 2 / pi * 360).round()} degree');
    this.startPolarCoord = null;
    widget.onDragEndFire?.call();
  }
}
